﻿using Ionic.Zip;
using SendMyZip.Classes;
using SendMyZip.DataAcess;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SendMyZip
{
    public partial class frmSendEmail : Form
    {
        private string _email, _password, _host, _port;
        private bool _emailInQueu = false;

        public frmSendEmail()
        {
            InitializeComponent();

            var setting = new Settings();
            _email = setting.GetEmail();
            _password = setting.GetPassword();
            _host = setting.GetHost();
            _port = setting.GetPort();
        }

        private void btnBrowseFile_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.
            {
                txtAttachment.Text = openFileDialog1.FileName;
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            // validate
            if (string.IsNullOrWhiteSpace(txtEmailTo.Text))
            {
                MessageBox.Show("Email to cannot be empty!", "Opp!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmailTo.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtAttachment.Text))
            {
                MessageBox.Show("Attachment cannot be empty!", "Opp!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnBrowseFile.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtSubject.Text))
            {
                MessageBox.Show("Subject cannot be empty!", "Opp!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtSubject.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtBodyToSend.Text))
            {
                MessageBox.Show("Body cannot be empty!", "Opp!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBodyToSend.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtPasswordToZip.Text))
            {
                MessageBox.Show("Password to zip file cannot be empty!", "Opp!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPasswordToZip.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtSubjectSendPassword.Text))
            {
                MessageBox.Show("Subject cannot be empty!", "Opp!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtSubjectSendPassword.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtBodyToSendPassword.Text))
            {
                MessageBox.Show("Body cannot be empty!", "Opp!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBodyToSendPassword.Focus();
                return;
            }

            if (MessageBox.Show("Are you sure you want to send this message?", "Hey budddy!",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            DisableAllControl();

            lblMessage.Text = "Sending email...";

            timer1.Interval = 2000;
            timer1.Start();

        }

        private void SendEmailProcess()
        {
            // send email process
            try
            {
                this._emailInQueu = true;

                var assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                var fileAttachmentPath = string.Empty;

                FileInfo fileInfo = new FileInfo(txtAttachment.Text);
                var destFilePath = assemblyPath + @"\" + fileInfo.Name;
                File.Copy(txtAttachment.Text, destFilePath);

                // zip attachment file
                using (var zip = new ZipFile())
                {
                    zip.Password = txtPasswordToZip.Text;
                    zip.AddFile(fileInfo.Name);
                    fileAttachmentPath = destFilePath + ".zip";
                    zip.Save(fileInfo.Name + ".zip");
                }

                // delete file copied
                File.Delete(destFilePath);

                // send email with attachment
                Email.Send(_email, _password, _host, _port, txtEmailTo.Text, txtSubject.Text, txtBodyToSend.Text, fileAttachmentPath);

                // delete zip file
                File.Delete(fileAttachmentPath);

                lblMessage.Text = "Send email with attachment successfully! The email includes password will be sent in " + txtSendInMinutes.Value + " minutes. Please don't close the window.";

            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
                EnableAllControl();
                this._emailInQueu = false;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            SendEmailProcess();
            // set timer
            timer2.Interval = int.Parse((txtSendInMinutes.Value * 60 * 1000).ToString());
            timer2.Start();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                timer2.Stop();
                // send email with password
                Email.Send(_email, _password, _host, _port, txtEmailTo.Text, txtSubjectSendPassword.Text, txtBodyToSendPassword.Text);

                lblMessage.Text = "Send email with password successfully!";

                EnableAllControl();
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }

            this._emailInQueu = false;
        }

        private void linkLabel1_Click(object sender, EventArgs e)
        {
            var si = new ProcessStartInfo("mailto:binh.pham@vietis.com.vn");
            Process.Start(si);
        }

        private void frmSendEmail_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this._emailInQueu)
            {
                MessageBox.Show("You cannot close the window when email is sending!", "Opp!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
                return;
            }
        }

        private void EnableAllControl()
        {
            txtEmailTo.Enabled = true;
            btnBrowseFile.Enabled = true;
            txtSubject.Enabled = true;
            txtBodyToSend.Enabled = true;
            txtPasswordToZip.Enabled = true;
            txtSubjectSendPassword.Enabled = true;
            txtBodyToSendPassword.Enabled = true;
            btnSend.Enabled = true;
            txtSendInMinutes.Enabled = true;
        }

        private void DisableAllControl()
        {
            txtEmailTo.Enabled = false;
            btnBrowseFile.Enabled = false;
            txtSubject.Enabled = false;
            txtBodyToSend.Enabled = false;
            txtPasswordToZip.Enabled = false;
            txtSubjectSendPassword.Enabled = false;
            txtBodyToSendPassword.Enabled = false;
            btnSend.Enabled = false;
            txtSendInMinutes.Enabled = false;
        }


    }
}
